package cn.edu.zut.soft.graduate.base.excel;

import cn.edu.zut.soft.graduate.base.excel.Excetion.HandleException;
import cn.edu.zut.soft.graduate.base.excel.pojo.FileType;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by chuchuang on 16/9/24.
 */
@Component
public class ExcelHandlerFactory {

    private final List<Map<String, String>> Empty = new ArrayList<>();

    public List<Map<String, String>> analysis(String ul, ExcelFileHandler excelFileHandler) throws IOException {
        //解析url,获取文件名与后缀名
        //获取流
        //
        URL url = new URL(ul);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.connect();
        if (conn.getResponseCode() / 100 != 2) {
            throw HandleException.create("url is error");
        }
        String[] ur = ul.split("/");
        String[] xl = ur[ur.length - 1].split("\\.");
        return analysis(conn.getInputStream(), xl[xl.length - 1], excelFileHandler);
    }

    public List<Map<String, String>> analysis(InputStream inputStream, String suffix, ExcelFileHandler excelFileHandler) {
        List<Map<String, String>> mapList;
        if (null == inputStream) {
            throw new NullPointerException("ExcelHandlerFactory.analysis inputStream is null");
        }
        if (StringUtils.isBlank(suffix)) {
            throw new NullPointerException("ExcelHandlerFactory.analysis suffix is null");
        }
        if (null == excelFileHandler) {
            throw new NullPointerException("ExcelHandlerFactory.analysis excelFileHandler is null");
        }
        if (!(suffix.equalsIgnoreCase(FileType.EXCEL.getName()) || suffix.equalsIgnoreCase(FileType.EXCELS.getName()))) {
            throw new IllegalArgumentException("ExcelHandlerFactory.analysis suffix not's xls or xlsx");
        }
        try {
            mapList = ExcelReader.read(inputStream, suffix);
        } catch (Exception e) {
            throw HandleException.create("ExcelHandlerFactoryanalysis ExcelReader.read is error", e);
        }
        if (mapList == null) {
            return Empty;
        }
        return excelFileHandler.handler(mapList);
    }

}
